package com.smooth.sys.site.biz.pic;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.smooth.common.pc.enums.RspStatus;
import com.smooth.common.site.common.config.Global;
import com.smooth.common.site.common.rsp.ReturnResult;
import com.smooth.common.site.common.utils.IdGenerater;
import com.smooth.sys.site.biz.pay.ali.sign.MD5Util;

@Controller
public class PcImgController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	IdGenerater idGenerater;
	@Value("${imgrootpath}")
	private String rootPath;
	@RequestMapping(value = { "${adminPath}/pic/img/upload" }, method = { RequestMethod.POST })
	@ResponseBody
	public ReturnResult add(HttpServletRequest request, HttpServletResponse response) {
		DefaultMultipartHttpServletRequest defaultMultipartHttpServletRequest = (DefaultMultipartHttpServletRequest)request;
		
		MultiValueMap<String, MultipartFile> mmap = defaultMultipartHttpServletRequest.getMultiFileMap();
		ReturnResult returnResult = new ReturnResult();
		if(!mmap.isEmpty()) {
			for (String key : mmap.keySet()) {
				List<MultipartFile> multipartFileList = mmap.get(key);
				String path = System.currentTimeMillis()+"";
				for(MultipartFile multipartFile : multipartFileList) {
					String oname = MD5Util.MD5(multipartFile.getOriginalFilename())+"."+multipartFile.getOriginalFilename().split("\\.")[1];
					String fileFolder = path+File.separator+idGenerater.genClsNo("pic")+File.separator;
					File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL+ fileFolder+ oname);
					if(!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					try {
						FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(file));
						String xx = Global.USERFILES_BASE_URL+fileFolder;
						xx = xx.replace("\\", "/").replace("//", "/");
						returnResult.setData(rootPath+xx+file.getName());
					} catch (Exception e) {
						logger.error("",e);
						returnResult.setStatus(RspStatus.FAILED.value);
						returnResult.setMessage(e.toString());
					}
					return returnResult;
				}
			}
		}
		return returnResult;
	}
	
	 /*
     * 图片按比率缩放
     * size为文件大小
     */
    public static void zoomImage(File srcFile,File destFile,Integer size) throws Exception {
        
        long fileSize = srcFile.length();
        if(fileSize < size * 1024)   //文件大于size k时，才进行缩放,注意：size以K为单位
            return;
        
        Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放比例
        
        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);
            
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,destFile.getAbsolutePath().substring(destFile.getAbsolutePath().lastIndexOf(".")+1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
	@RequestMapping(value = { "pc/p/pic/img/upload" }, method = { RequestMethod.POST })
	@ResponseBody
	public ReturnResult picUpload(HttpServletRequest request, HttpServletResponse response) {
		return add(request,response);
	}
	
}
